<?php
namespace Plu\Library\Plugins;

use Phalcon\Mvc\User\Plugin,
	Plu\Library\Models\Platform\Permission\PermissionRoleOfUser,
	Plu\Library\Models\Platform\Permission\PermissionResource;

class PermissionCheckerPlugin extends Plugin {
	
	public function beforeExecuteRoute($event, $dispatcher) {
		$annotations = $this->annotations->getMethod(
			$dispatcher->getControllerClass(),
			$dispatcher->getActiveMethod()
		);
		
		if ($annotations->has('checkAdminPermission')) {
			$this->checkAdminPermission();
		}

	}

	public function afterExecuteRoute($event, $dispatcher) {
		$annotations = $this->annotations->getMethod(
			$dispatcher->getControllerClass(),
			$dispatcher->getActiveMethod()
		);
	}


	private function throwStatus406() {
		$this->response->setStatusCode(406, "Not Acceptable");
		$this->response->send();
		exit;
	}

	/**
	 * 检查管理员权限
	 */
	private function checkAdminPermission($annotation) {
		if (!$this->passport) {
			return false;
		}
		
		$uid = $this->passport->isLogined();

		if ($uid <= 0) {
			return $this->checkLogin($annotation);
		}
		$roles = PermissionRoleOfUser::getRoles($uid);

		if ($roles === false) {
			return $this->throwStatus406();
		}
		$tag = $annotation->getNamedArgument('tag');

		//如果为空 直接放权限回去
		if (empty($tag)) {
			return true;
		}

		$roleInfo = PermissionResource::getResourceByIdentification($tag, $roles);
		//计算当前的role是否符合此权限
		if ($roleInfo == false) {
			return $this->throwStatus406();
		}
	}
}
?>
